package com.yuyou.tas.terminal.controller;

import com.alibaba.fastjson.JSONObject;
import com.yuyou.tas.service.api.admin.entity.AuthUser;
import com.yuyou.tas.service.api.admin.service.AuthUserAPI;
import com.yuyou.tas.service.api.admin.service.CommMessPushAPI;
import com.yuyou.tas.service.api.admin.vo.WxMpTemplateDataVo;
import com.yuyou.tas.service.api.admin.vo.WxMpTemplateMessageVo;
import com.yuyou.tas.service.api.feedback.dto.ExceStudentDTO;
import com.yuyou.tas.service.api.feedback.dto.FeedbackCommentDTO;
import com.yuyou.tas.service.api.feedback.dto.FeedbackDetailDTO;
import com.yuyou.tas.service.api.feedback.dto.FeedbackListDTO;
import com.yuyou.tas.service.api.feedback.entity.Feedback;
import com.yuyou.tas.service.api.feedback.entity.FeedbackNote;
import com.yuyou.tas.service.api.feedback.service.*;
import com.yuyou.tas.service.api.feedback.vo.resp.FeedbackNameResp;
import com.yuyou.tas.service.api.lesson.entity.BaseTrimester;
import com.yuyou.tas.service.api.lesson.entity.Student;
import com.yuyou.tas.service.api.lesson.service.StudentAPI;
import com.yuyou.tas.terminal.comm.MUAPI;
import com.yuyou.tas.terminal.comm.YyfnTAPI;
import com.yuyou.tas.terminal.vo.ReqMU.ReqFeedbackList;
import com.yuyou.tas.terminal.vo.ReqMU.ReqMUBase;
import com.yuyou.tas.util.bean.PageParams;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.bean.ReturnResult;
import com.yuyou.tas.util.enums.admin.CommMessPushEnums;
import com.yuyou.tas.util.enums.feedback.FeedbackCommentEnums;
import com.yuyou.tas.util.enums.feedback.FeedbackEnums;
import com.yuyou.tas.util.tool.BeanUtils;
import com.yuyou.tas.util.tool.HttpClient;
import com.yuyou.tas.util.tool.LogUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.*;

@Api(value="YyfnMUFeedbackController",description="学生端反馈接口")
@Validated
@RestController
@RequestMapping(value = "/api/m/u/feedback")
public class YyfnMUFeedbackController extends YyfnMUController{

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${feedback.wetchat.push.url}")
	public String PUSH_URL;

	@Value("${feedback.wetchat.push.templateId}")
	public String TEMPLATEID;

	@Value("${feedback.wetchat.jump.templateId}")
	public String JUMP_URL;

	//消息推送首行文字
	public static String FIRST_WORD = "你有一条新的反馈消息。为提高服务质量，请及时查看。";

    //消息推送首行文字
    public static String LAST_WORD = "点击详情查看反馈内容。";

	@Autowired
	private StudentAPI studentAPI;

	@Autowired
	private CommMessPushAPI commMessPushAPI;

	@Autowired
	private MUAPI mUAPI;

	@Autowired
	private FeedbackAPI feedbackAPI;

	@Autowired
	private FeedbackCommentAPI feedbackCommentAPI;

	@Autowired
	private FeedbackPraiseAPI feedbackPraiseAPI;

	@Autowired
	private FeedbackStudentExceAPI feedbackStudentExceAPI;

	@Autowired
	private FeedbackNoteAPI feedbackNoteAPI;

	@Autowired
	private YyfnTAPI yyfnTAPI;

	@Autowired
	private AuthUserAPI authUserAPI;
	
	@ApiOperation(value = "查询学生反馈列表")
	@RequestMapping(value = "/feedbackList", method = { RequestMethod.GET,RequestMethod.POST })
	public ReturnResult<List<FeedbackListDTO>> findFeedList(HttpServletRequest request,
															@Validated @ModelAttribute PageParams pageParams,
															@Validated @ModelAttribute ReqFeedbackList reqFeedbackList) throws Exception {

		ResBoolSimpleInfo<String> resStu = mUAPI.validaStu(reqFeedbackList.getAccessToken(), reqFeedbackList.getStudentId());
		if(!resStu.isSuccess()){
			return ReturnResult.fail(resStu.getMessage());
		}

		//转换成 tas 学生
		Student student = this.getTasStudent(reqFeedbackList.getAccessToken(),reqFeedbackList.getSysCode(), reqFeedbackList.getStudentId());

		Map<String, Object> conditions = new HashMap<>();
		Pagination<FeedbackListDTO> queryPgn = new Pagination<>();
		conditions.put("studentId", student.getId());
		conditions.put("status", FeedbackEnums.status.published.getValue());
		conditions.put("dataSubject", reqFeedbackList.getDataSubject());
		conditions.put("baseTrimesterId", reqFeedbackList.getBaseTrimesterId());
		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);

		int total = feedbackAPI.findFeedbackCount(queryPgn);
		queryPgn.setTotal(total);
		queryPgn.toBePage();
		if(total > 0){
			List<FeedbackListDTO> list = feedbackAPI.feedbackList(queryPgn);
			queryPgn.setList(list);
		}

		return ReturnResult.success(queryPgn);
	}
	
	@ApiOperation(value = "查询学生反馈详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "feedbackId", value = "反馈ID不能为空", paramType = "query", required = true),
			@ApiImplicitParam(name = "feedbackClassId", value = "反馈班级ID不能为空", paramType = "query", required = true)
	})
	@RequestMapping(value = "/feedbackDetail", method = { RequestMethod.GET, RequestMethod.POST })
	public ReturnResult<FeedbackDetailDTO> feedbackDetail(HttpServletRequest request,
														  @Validated @ModelAttribute ReqMUBase reqMUBase,
														  @NotNull(message = "反馈ID不能为空") Long feedbackId,
														  @NotNull(message = "反馈班级ID不能为空") Long feedbackClassId) throws Exception {
		//转换学生ID
		Student student = this.getTasStudent(reqMUBase.getAccessToken(),reqMUBase.getSysCode(), reqMUBase.getStudentId());

		FeedbackDetailDTO feedbackDetailDTO = feedbackAPI.feedbackDetail(feedbackId);
		feedbackDetailDTO.setStudentName(student.getName());
		feedbackDetailDTO.setPraiseSum(feedbackPraiseAPI.countPraiseByFeedbackClassId(feedbackClassId));
		feedbackDetailDTO.setIfPraise(feedbackPraiseAPI.countPraiseByFeedbackClassIdUserId(feedbackClassId, student.getId()) > 0 ? 1 : 0);
		return ReturnResult.success(feedbackDetailDTO);
	}
	
	@ApiOperation(value = "发表反馈评论")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "feedbackId", value = "反馈ID不能为空", paramType = "query", required = true),		
			@ApiImplicitParam(name = "content", value = "内容不能为空", paramType = "query", required = true)
			})
	@RequestMapping(value = "/addFeedbackComment", method = { RequestMethod.GET,RequestMethod.POST })
	public ReturnResult<String> addFeedbackComment(HttpServletRequest request,
															@Validated @ModelAttribute ReqMUBase reqMUBase,
															@NotNull(message = "反馈ID不能为空") Long feedbackId,
															@NotBlank(message = "内容不能为空") String content) throws Exception {
		ResBoolSimpleInfo<String> resStu = mUAPI.validaStu(reqMUBase.getAccessToken(), reqMUBase.getStudentId());
		if(!resStu.isSuccess()){
			return ReturnResult.fail(resStu.getMessage());
		}
		//转换学生ID
		Student student = this.getTasStudent(reqMUBase.getAccessToken(),reqMUBase.getSysCode(), reqMUBase.getStudentId());
		Feedback feedback = feedbackAPI.selectByPrimaryKey(feedbackId);
		if(feedback != null){
			Long id = feedbackCommentAPI.saveFeedbackComment(feedbackId, content, student.getAuthOrganizationId(), student.getId(),FeedbackCommentEnums.userType.stu.getValue());
			AuthUser teacher = authUserAPI.selectById(feedback.getCreateUser());
			if(teacher != null && teacher.getoId() != null){
				//推送教师公众号提醒消息
				List<String> openIds = yyfnTAPI.getTeacherDetail(teacher.getoId());
				if(!CollectionUtils.isEmpty(openIds)){
					openIds.forEach(s -> this.pushMess(id, student.getName() ,student.getId(), s , feedbackId , reqMUBase.getSysCode()));
				}
			}
		}

		return ReturnResult.success("OK");
	}
	
	
	@ApiOperation(value = "送花给反馈的老师")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "feedbackClassId", value = "反馈 ID 不能为空", paramType = "query", required = true),
			@ApiImplicitParam(name = "teacherId", value = "老师 ID 不能为空", paramType = "query", required = true)
			})
	@RequestMapping(value = "/addfeedbackPraise", method = { RequestMethod.GET,	RequestMethod.POST })
	public ReturnResult<List<BaseTrimester>> addfeedbackPraise(HttpServletRequest request,
														       @Validated @ModelAttribute ReqMUBase reqMUBase,
														       @NotNull(message = "反馈班级 ID 不能为空") Long feedbackClassId,
														       @NotNull(message = "老师 ID 不能为空") Long teacherId) throws Exception {
		ResBoolSimpleInfo<String> resStu = mUAPI.validaStu(reqMUBase.getAccessToken(), reqMUBase.getStudentId());
		if(!resStu.isSuccess()){
			return ReturnResult.fail(resStu.getMessage());
		}
		//转换学生ID
		Student student = this.getTasStudent(reqMUBase.getAccessToken(),reqMUBase.getSysCode(), reqMUBase.getStudentId());
		feedbackPraiseAPI.saveFeedbackPraise(feedbackClassId, teacherId, student.getId(), student.getAuthOrganizationId());
		return ReturnResult.success("OK");
	}

	@ApiOperation(value = "优秀学生名单")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "feedbackClassId", value = "反馈 ID 不能为空", paramType = "query", required = true)
	})
	@RequestMapping(value = "/exceStudentList", method = { RequestMethod.GET,	RequestMethod.POST })
	public ReturnResult<List<ExceStudentDTO>> exceStudentList(HttpServletRequest request,
															  @Validated @ModelAttribute ReqMUBase reqMUBase,
															  @NotNull(message = "反馈班级 ID 不能为空") Long feedbackClassId) throws Exception {
		ResBoolSimpleInfo<String> resStu = mUAPI.validaStu(reqMUBase.getAccessToken(), reqMUBase.getStudentId());
		if(!resStu.isSuccess()){
			return ReturnResult.fail(resStu.getMessage());
		}
		//转换学生ID
		Student student = this.getTasStudent(reqMUBase.getAccessToken(),reqMUBase.getSysCode(), reqMUBase.getStudentId());
		List<ExceStudentDTO> exceStudentList = feedbackStudentExceAPI.findExceStudentByFeedbackClassId(feedbackClassId);
		// 本人是优秀学生，排第一
		List<Long> exeStudentIds = BeanUtils.toList(exceStudentList, "id");
		if(exeStudentIds.contains(student.getId())){
			for(int i = 0 ;i < exceStudentList.size() ; i++){
				if(exceStudentList.get(i).getId().equals(student.getId())){
					Collections.swap(exceStudentList, 0, i);
					break;
				}
			}
		}

		return ReturnResult.success(exceStudentList);
	}

	@ApiOperation(value = "优秀学生笔记")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "feedbackClassId", value = "反馈 ID 不能为空", paramType = "query", required = true)
	})
	@RequestMapping(value = "/feedbackNoteList", method = { RequestMethod.GET,	RequestMethod.POST })
	public ReturnResult<List<FeedbackNote>> feedbackNoteList(HttpServletRequest request,
															 @Validated @ModelAttribute ReqMUBase reqMUBase,
															 @NotNull(message = "反馈班级 ID 不能为空") Long feedbackClassId) throws Exception {
		ResBoolSimpleInfo<String> resStu = mUAPI.validaStu(reqMUBase.getAccessToken(), reqMUBase.getStudentId());
		if(!resStu.isSuccess()){
			return ReturnResult.fail(resStu.getMessage());
		}
		//转换学生ID
//		Student student = this.getTasStudent(reqMUBase.getSysCode(), reqMUBase.getStudentId());
		List<FeedbackNote> feedbackNoteList = feedbackNoteAPI.findNoteByFeedbackClassId(feedbackClassId);
		return ReturnResult.success(feedbackNoteList);
	}

	@ApiOperation(value = "评论列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "feedbackId", value = "反馈 ID 不能为空", paramType = "query", required = true)
	})
	@RequestMapping(value = "/feedbackCommentList", method = { RequestMethod.GET,	RequestMethod.POST })
	public ReturnResult<List<FeedbackCommentDTO>> feedbackCommentList(HttpServletRequest request,
																	  @Validated @ModelAttribute ReqMUBase reqMUBase,
																	  @NotNull(message = "反馈 ID 不能为空") Long feedbackId) throws Exception {
		ResBoolSimpleInfo<String> resStu = mUAPI.validaStu(reqMUBase.getAccessToken(), reqMUBase.getStudentId());
		if(!resStu.isSuccess()){
			return ReturnResult.fail(resStu.getMessage());
		}
		//转换学生ID
//		Student student = this.getTasStudent(reqMUBase.getSysCode(), reqMUBase.getStudentId());
		List<FeedbackCommentDTO> feedbackCommentList = feedbackCommentAPI.feedbackCommentList(feedbackId);
		return ReturnResult.success(feedbackCommentList);
	}

	/**
	 * 推送消息
	 * @param feedbackCommentId
	 */
	public void pushMess(Long feedbackCommentId , String stuName ,Long stuId, String openId , Long feedbackId , String sysCode){
		//发送微信公众号消息推送
		new Thread(() -> {

			//插入记录时间resp
			commMessPushAPI.addJob(feedbackCommentId ,
					CommMessPushEnums.TYPE.FEEDBACK_COMMENT_REMIND.getValue(),
					CommMessPushEnums.STATUS.INIT.getValue(),
					CommMessPushEnums.TAG.FEEDBACK_COMMENT_REMIND.getValue());

			String res = null;
			try {
				FeedbackNameResp resp = feedbackAPI.getFeedbackName(feedbackId);
				if(resp != null){
					WxMpTemplateMessageVo wxMpTemplateMessageVo = new WxMpTemplateMessageVo();
					wxMpTemplateMessageVo.setTemplateId(TEMPLATEID);
					wxMpTemplateMessageVo.setToUser(openId);
					wxMpTemplateMessageVo.setUrl(JUMP_URL + "feedbackClassId="
							+ resp.getFeedbackClassId() + "&sysCode="
							+ sysCode + "&openId=" + openId + "&teacherId=" + resp.getTeacherId() + "&stuId=" + stuId);

					logger.info(wxMpTemplateMessageVo.getUrl());
					List<WxMpTemplateDataVo> l = new ArrayList<>();

                    //学生名称参数
                    WxMpTemplateDataVo wt = new WxMpTemplateDataVo();
                    wt.setColor("#000");
                    wt.setName("first");
                    wt.setValue(YyfnMUFeedbackController.FIRST_WORD);
                    l.add(wt);

					//班级信息参数
					WxMpTemplateDataVo wt1 = new WxMpTemplateDataVo();
					wt1.setColor("#459ae9");
					wt1.setName("keyword1");
					wt1.setValue(resp.getClassName());
					l.add(wt1);

					//反馈创建时间参数
					WxMpTemplateDataVo wt2 = new WxMpTemplateDataVo();
					wt2.setColor("#459ae9");
					wt2.setName("keyword2");
					wt2.setValue(resp.getTimeForamt());
					l.add(wt2);

					//学生名称参数
					WxMpTemplateDataVo wt3 = new WxMpTemplateDataVo();
					wt3.setColor("#459ae9");
					wt3.setName("keyword3");
					wt3.setValue(stuName);
					l.add(wt3);

                    //末行
                    WxMpTemplateDataVo wt4 = new WxMpTemplateDataVo();
                    wt4.setColor("#000");
                    wt4.setName("remark");
                    wt4.setValue(YyfnMUFeedbackController.LAST_WORD);
                    l.add(wt4);

					wxMpTemplateMessageVo.setData(l);

					Map<String, String> params=new HashMap<String, String>();
					params.put("templateMessageJson", JSONObject.toJSON(wxMpTemplateMessageVo).toString());
					res = HttpClient.post(PUSH_URL, params,null);
				}

			} catch (Exception e) {
				commMessPushAPI.updateJobStatusByFId(feedbackCommentId , CommMessPushEnums.STATUS.FAIL.getValue() , e.getMessage());
				LogUtil.error(logger , "微信公众消息推送失败" , e);
				return;
			}

			if(StringUtils.isNotEmpty(res) && !res.equalsIgnoreCase("ok")){
				commMessPushAPI.updateJobStatusByFId(feedbackCommentId , CommMessPushEnums.STATUS.SUCCESS.getValue() , res);
			}else {
				commMessPushAPI.updateJobStatusByFId(feedbackCommentId , CommMessPushEnums.STATUS.FAIL.getValue() , res);
			}
		}).start();
	}

    /*public static void main(String[] args) {
        WxMpTemplateMessageVo wxMpTemplateMessageVo = new WxMpTemplateMessageVo();
        wxMpTemplateMessageVo.setTemplateId("FqZZ2Hd277MoA3CKhqSaNIRBzf2");
        wxMpTemplateMessageVo.setToUser("oiWL9wC2PpdWdVpEyzgK0MxRtHSI");
        wxMpTemplateMessageVo.setUrl("");

        List<WxMpTemplateDataVo> l = new ArrayList<>();

        //学生名称参数
        WxMpTemplateDataVo wt = new WxMpTemplateDataVo();
        wt.setColor("#000");
        wt.setName("first");
        wt.setValue(String.format(YyfnMUFeedbackController.FIRST_WORD , "test1"));
        l.add(wt);

        //班级信息参数
        WxMpTemplateDataVo wt1 = new WxMpTemplateDataVo();
        wt1.setColor("#459ae9");
        wt1.setName("keyword1");
        wt1.setValue("test2");
        l.add(wt1);

        //反馈创建时间参数
        WxMpTemplateDataVo wt2 = new WxMpTemplateDataVo();
        wt2.setColor("#459ae9");
        wt2.setName("keyword2");
        wt2.setValue("test3");
        l.add(wt2);

        //学生名称参数
        WxMpTemplateDataVo wt3 = new WxMpTemplateDataVo();
        wt3.setColor("#459ae9");
        wt3.setName("keyword3");
        wt3.setValue("test4");
        l.add(wt3);

        //末行
        WxMpTemplateDataVo wt4 = new WxMpTemplateDataVo();
        wt4.setColor("#000");
        wt4.setName("remark");
        wt4.setValue(YyfnMUFeedbackController.LAST_WORD);
        l.add(wt4);

        wxMpTemplateMessageVo.setData(l);

        System.out.println(JSONObject.toJSON(wxMpTemplateMessageVo).toString());
    }*/
}
